package org.ruizhijie.run;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ruizhijie.i.IPublisher;
import org.ruizhijie.util.CharUtil;

public class InPortV2 implements Runnable {
	private Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

	private IPublisher pub;
	private int port;
	private DatagramSocket ds;
	private byte[] b = new byte[7];
	private DatagramPacket pack = new DatagramPacket(b, 0, b.length);

	public InPortV2(IPublisher publish, int port) {
		this.pub = publish;
		this.port = port;
		System.out.println(port);
		try {
			ds = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}

		log.info("in 初始化完成");

	}

	@Override
	public void run() {
		while (true) {
			try {
				ds.receive(pack);
				
				pub.publish(""+port, pack.getData());
				
				log.info("read 收到读卡器消息: "+CharUtil.bytesToHexString(pack.getData()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
